package br.edu.infnet.avaliacao.dao.hibernate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Scanner;

import org.hibernate.Session;

public abstract class GenericDAO {

	public Connection getConexao() {
		Connection conexao = null;
		try {
			Class.forName("org.postgresql.Driver");
			conexao = DriverManager.getConnection(
					"jdbc:postgresql://localhost:5432/BDUsuario", "postgres",
					"teco01");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conexao;
	}

	public final Integer MAXIMO_REGISTROS = 1000;
	protected Session session = HibernateUtil.getSessionFactory().openSession();

	public Session getSession() {
		return HibernateUtil.getSession();
	}

	protected Date lerData(java.sql.Date data) {
		Date d = null;
		try {
			d = new Date(data.getTime());
		} catch (Exception e) {
			d = new Date();
		}
		return d;
	}

	protected String lerString(String texto) {
		String novoTexto = "";

		if (texto != null) {
			novoTexto = texto.trim();
		}
		return novoTexto;
	}

	protected String nomeToLowerCase(String nome) {
		nome = nome.toLowerCase().replaceAll("  ", " ");

		Scanner sc = new Scanner(nome);
		sc.useDelimiter(" ");
		StringBuilder sb = new StringBuilder(nome.length());
		while (sc.hasNext()) {
			String s = sc.next().trim();
			if ((s.length() >= 3) || (s.length() == 1)
					|| (s.length() == 2 && s.contains("."))) {
				sb.append((" " + s.charAt(0)).toUpperCase() + s.substring(1));
			} else {
				sb.append(" " + s);
			}

		}
		sc.close();
		return sb.toString().trim();
	}

	public Connection getConexaoNativa() throws SQLException {
		return HibernateUtil.getConexaoNativa();
	}
}